#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
    static bool cmp(vector<int> &a, vector<int>&b){
        if(a[0]!=b[0]) return a[0]<b[0];
        else return a[1]<b[1];
    }
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
        vector<vector<int>> ans;

        sort(intervals.begin(), intervals.end(), cmp);
        int n = intervals.size();
        int left = intervals[0][0];
        int right = intervals[0][1];
        for(int i=1; i<n; ++i){
            if(intervals[i][0]<=right){
                right = max(intervals[i][1], right);
            }
            else {
                vector<int> tmp = {left, right};
                ans.push_back(tmp);
                left = intervals[i][0];
                right = intervals[i][1];
            }
        }
        vector<int> tmp = {left, right};
        ans.push_back(tmp);
        return ans;
    }
};